#include "Done.hh"
#include "GetGameList.hh"
#include "XmlClient.hh"
#include "../Exception.hh"

using namespace Network;

spDone Done::construct(QDomElement const& message) {
    QDomElement const statusElem = message.firstChildElement("status");
    QDomElement const messageElem = message.firstChildElement("message");
    QDomNode const statusNode = statusElem.firstChild();
    QDomNode const messageNode = messageElem.firstChild();
    QDomText const statusText = statusNode.toText();
    QDomText const messageText = messageNode.toText();
    QString const statusStr = statusText.nodeValue();
    QString const messageStr = messageText.nodeValue();
    bool statusBool;

    if (statusElem.isNull() || !statusNode.isText())
        throw NonFatalProtocolError("done.status missing or invalid");

    if (messageElem.isNull() || !messageNode.isText())
        throw NonFatalProtocolError("done.message missing or invalid");

    if (statusStr == "true")
        statusBool = true;
    else if (statusStr == "false")
        statusBool = false;
    else
        throw NonFatalProtocolError("done.status invalid");

    return spDone(new Done(statusBool, messageText.toText().nodeValue()));
}

Done::Done(bool status, QString const& message):
    status(status),
    message(message) {}

void Done::process_on_client(XmlClient& client) {
    switch (client.get_state()) {

       /* case AUTH_RESPONSE_SENT:
            if (status) {
                client.set_state(AUTHENTICATED);
                client.show_main_window();
                GetGameList getGameList;
                getGameList.send_to(client.get_socket());
            } else {
                client.set_state(START);
            }

            break;*/

        case INIT_NEW_GAME_SENT:
        {
        	if (status) {
        		client.show_game_window();
        	} else {
        		client.message("nem sikerült játékot létrehozni");
        	}
            break;
        }

        case NEXT_TURN_SENT:
        {
        	if (!status) {
        		client.message("nem sikerült befejezni a kört");
        	}
            break;
        }

        case INIT_JOIN_SENT:
        {
        	if (status) {
        		client.show_game_window();
        	} else {
        		client.message("nem sikerült csatlakozni");
        	}
        	break;
        }


        default:
            throw ProtocolError("done unexpected");
    }
}

QDomDocument Done::to_xml() const {
    QDomDocument doc;
    QDomElement done = doc.createElement("done");
    QDomElement statusElem = doc.createElement("status");
    QDomElement messageElem = doc.createElement("message");
    QDomText statusText = doc.createTextNode(status ? "true" : "false");
    QDomText messageText = doc.createTextNode(message);
    doc.appendChild(done);
    done.appendChild(statusElem);
    done.appendChild(messageElem);
    statusElem.appendChild(statusText);
    messageElem.appendChild(messageText);
    return doc;
}
